package com.ningmengs789.live.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.ningmengs789.live.ActivityUtils;
import com.ningmengs789.live.App;
import com.ningmengs789.live.Const;
import com.ningmengs789.live.R;
import com.ningmengs789.live.http.OKHttpUtils;
import com.ningmengs789.live.Interface.RequestCallback;
import com.ningmengs789.live.net.response.AdLaunchScreenResponse;
import com.ningmengs789.live.net.utils.NToast;
import com.ningmengs789.live.net.utils.json.JsonMananger;
import com.ningmengs789.live.utils.IPermissions;
import com.ningmengs789.live.utils.PermissionsUtils;
import com.ningmengs789.live.net.network.http.HttpException;
import com.ningmengs789.live.utils.UserInfoUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.xinstall.XInstall;
import com.xinstall.listener.XWakeUpAdapter;
import com.xinstall.model.XAppData;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Map;

public class SplashActivity extends BaseActivityH implements IPermissions {

    private Context mContext;
    private ImageView splashImg;
    private Button splash_btn;
    private boolean isResume = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        mContext = this;
        splashImg = findViewById(R.id.splash_img);
        splash_btn = findViewById(R.id.splash_btn);

        PermissionsUtils.initPermission(mContext);

        //获取唤醒参数
        XInstall.getWakeUpParam(getIntent(), wakeUpAdapter);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 此处要调用，否则App在后台运行时，会无法截获
        XInstall.getWakeUpParam(getIntent(), wakeUpAdapter);
    }

    XWakeUpAdapter wakeUpAdapter = new XWakeUpAdapter() {
        @Override
        public void onWakeUp(XAppData XAppData) {
            //获取渠道数据
//            String channelCode = XAppData.getChannelCode();

            //获取数据
            Map<String, String> data = XAppData.getExtraData();
            //通过链接后面携带的参数或者通过webSdk初始化传入的data值。
            String uo = data.get("uo");

            if (uo != null){
                //uo {"from_uid":"20003","r":"1606450298"}
                try {
                    String from_uid = new JSONObject(uo).getString("from_uid");
                    if (!TextUtils.isEmpty(from_uid)){
                        UserInfoUtil.setFromUid(from_uid);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            //webSdk初始，在buttonId里面定义的按钮点击携带数据
//            String co = data.get("co");

            //获取时间戳
//            String timeSpan = XAppData.getTimeSpan();

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        wakeUpAdapter = null;
    }

    private void startApp() {
        String launch_img = UserInfoUtil.getLaunchImg();
        if (!TextUtils.isEmpty(launch_img)){
            Glide.with(mContext)
                    .load(com.ningmengs789.live.utils.CommonUtils.getUrl(launch_img))
                    .transition(new DrawableTransitionOptions().crossFade(1500))
                    .into(splashImg);
            final String link = UserInfoUtil.getLaunchLink();
            splashImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(link)) {
                        Intent intent = new Intent("io.xchat.intent.action.webview");
                        intent.setPackage(mContext.getPackageName());
                        intent.putExtra("url", link);
                        startActivity(intent);
                    }
                }
            });
        }
        goToMain();
    }

    private void goToMain() {
        if (!isResume){
            return;
        }
        splash_btn.setVisibility(View.VISIBLE);
        splash_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.removeCallbacks(runnable);
                startActi();
            }
        });

        mHandler.postDelayed(runnable, 4000);
    }

    protected Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            startActi();
        }
    };

    private void startActi(){
        ActivityUtils.startHome(mContext);
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResume = false;
        mHandler.removeCallbacks(runnable);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
        PermissionsUtils.onResumeSplash(this, this);
    }

    @Override
    public void allPermissions() {
        createFloder();

        OKHttpUtils.getInstance().getRequest("app/public/configIssue", "", new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                NToast.shortToast(mContext, errInfo);
            }
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject data = new JSONObject(result);
                    JSONObject config = data.getJSONObject("config");
                    JSONObject trtc = config.getJSONObject("trtc");
                    String live_key = trtc.getString("live_key");
                    String live_license_url = trtc.getString("live_license_url");
                    String shortvideo_key = trtc.getString("shortvideo_key");
                    String shortvideo_license_url = trtc.getString("shortvideo_license_url");

                    int app_id = trtc.getInt("app_id");

                    Const.im_app_id = app_id;
                    App.iSDKID(app_id);
                    App.TX(live_key, live_license_url, shortvideo_key, shortvideo_license_url);

                    String object_domain = config.getString("object_domain");
                    Const.domain_url2 = object_domain;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                startApp();
            }
        });

        //app/public/configIssue
        OKHttpUtils.getInstance().getRequest("app/ad/adLaunchScreen", "", new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                UserInfoUtil.setLaunch("", "");
            }
            @Override
            public void onSuccess(String result) {
                try {
                    AdLaunchScreenResponse response = JsonMananger.jsonToBean(result, AdLaunchScreenResponse.class);
                    if (response.getList().size() == 0){
                        UserInfoUtil.setLaunch("", "");
                        return;
                    }
                    UserInfoUtil.setLaunch(response.getList().get(0).getImg(), response.getList().get(0).getLink());
                } catch (HttpException e) {
                    e.printStackTrace();
                    UserInfoUtil.setLaunch("", "");
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this, this, false);
    }

    private void createFloder() {
        File file0 = new File(Const.REAL_PIC_PATH);
        if (!file0.isDirectory()) {
            file0.mkdirs();
        }
        File file = new File(Const.voiceDir);
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        File file1 = new File(Const.cropDir);
        if (!file1.isDirectory()) {
            file1.mkdirs();
        }
        File file2 = new File(Const.downloadDir);
        if (!file2.isDirectory()) {
            file2.mkdirs();
        }

    }
}
